// js/pages/HomePage.js
import BasePage from './BasePage.js';
import TextRenderer from '../utils/TextRenderer.js';
import DailyLoginDialog from '../ui/DailyLoginDialog.js';
import myFn from '../utils/myFn.js';

// 提取常量
const UI_CONSTANTS = {
  TOP_SECTION: {
    AVATAR: { X: 44, Y: 18, WIDTH: 68, HEIGHT: 68 },
    USERNAME: { X: 148, Y: 40 },
    SHARE_TEXT: { X: 1040, Y: 40 },
    SHARE_ICON: { X: 1296, Y: 22, WIDTH: 58, HEIGHT: 58 }
  },
  CENTER_MENU: {
    X: 160,
    Y: 140,
    SPACING: 115,
    WIDTH: 358,
    HEIGHT: 476
  },
  BOTTOM_MENU: {
    X: 0,
    Y: 650,
    SPACING: 1,
    WIDTH: 324,
    HEIGHT: 98,
    ITEM_Y_OFFSET: 40
  },
  DAILY_LOGIN: {
    CLAIM_BUTTON: { X: 700, Y: 592, WIDTH: 239, HEIGHT: 88 }
  },
  REWARD_POPUP: {
    BUTTON_Y: 546,
    PLUS_X: 750,
    PLUS_Y: 355,
    BONUS_X: 810,
    BONUS_Y: 340
  },
  COLORS: {
    TEXT_WHITE: '#ffffff',
    TEXT_YELLOW: '#FDDF64',
    TEXT_LIGHT: '#FCF4C4'
  },
  FONT_SIZES: {
    USERNAME: 28,
    SHARE: 28,
    BOTTOM_MENU: 32,
    REWARD_PLUS: 60,
    REWARD_BONUS: 80,
    REWARD_BUTTON: 32
  }
};

// 底部菜单项配置
const BOTTOM_MENU_ITEMS = [
  { name: '排行榜', icon: '🏆', page: 'leaderboard' },
  { name: '学院', icon: '🎓', page: null },
  { name: '公告', icon: '📢', page: null },
  { name: '客服', icon: '👨‍💼', page: null }, // 客服功能暂未实现
  { name: '教程', icon: '📚', page: null } // 教程功能暂未实现
];

// 中间菜单项配置
const CENTER_MENU_ITEMS = [
  { name: '练习场', imageKey: 'practiceBtn', page: 'game' },
  { name: '排位赛', imageKey: 'rankingBtn', page: null },// 排位赛功能暂未实现
  { name: '挑战赛', imageKey: 'challengeBtn', page: null } // 挑战赛功能暂未实现
];

export default class HomePage extends BasePage {
  constructor(canvas, ctx, pageManager, resourceManager, screenAdapter, api, userManager) {
    super(canvas, ctx, pageManager);
    this.resourceManager = resourceManager;
    this.screenAdapter = screenAdapter;
    this.api = api;
    this.userManager = userManager;
    this.textRenderer = new TextRenderer(ctx, screenAdapter);
    this.centerMenu = null;
    this.bottomMenu = null;
    this.dailyLoginDialog = null;
    this.showDailyLoginDialog = false;
    this.showReward = false;
    this.bonus = 0;
    this.isInitialized = false;
  }

  onInit() {
    return Promise.resolve();
  }

  /**
   * 页面初始化方法
   */
  async initialize() {
    try {
      this.resetState();
      await this.initializeUI();
      await this.fetchGameData();
      this.isInitialized = true;
    } catch (error) {
      console.error('主页初始化失败:', error);
      throw error;
    }
  }

  /**
   * 重置页面状态
   */
  resetState() {
    this.showDailyLoginDialog = false;
    this.showReward = false;
    this.bonus = 0;
  }

  /**
   * 初始化UI元素
   */
  initializeUI() {
    this.centerMenu = {
      x: UI_CONSTANTS.CENTER_MENU.X,
      y: UI_CONSTANTS.CENTER_MENU.Y,
      spacing: UI_CONSTANTS.CENTER_MENU.SPACING,
      width: UI_CONSTANTS.CENTER_MENU.WIDTH,
      height: UI_CONSTANTS.CENTER_MENU.HEIGHT
    };

    this.bottomMenu = {
      x: UI_CONSTANTS.BOTTOM_MENU.X,
      y: UI_CONSTANTS.BOTTOM_MENU.Y,
      spacing: UI_CONSTANTS.BOTTOM_MENU.SPACING,
      width: UI_CONSTANTS.BOTTOM_MENU.WIDTH,
      height: UI_CONSTANTS.BOTTOM_MENU.HEIGHT
    };

    this.dailyLoginDialog = new DailyLoginDialog({
      x: 0,
      y: 104,
      width: 1454,
      height: 530,
      signDays: this.userManager.getUserData().sign_in_days,
      signDate: this.userManager.getUserData().sign_in_date
    }, this.textRenderer, this.screenAdapter, this.resourceManager);
  }

  /**
   * 获取游戏数据
   */
  async fetchGameData() {
    try {
      const userData = this.userManager.getUserData();
      this.showDailyLoginDialog = !myFn.isToday(userData.sign_in_date, userData.sign_in_days);
    } catch (error) {
      console.error('获取游戏数据失败:', error);
    }
  }

  /**
   * 渲染页面
   */
  render() {
    if (!this.isInitialized) return;

    this.renderBackground();
    this.renderTopSection();
    this.renderMiddleSection();
    this.renderBottomSection();

    if (this.showDailyLoginDialog) {
      this.renderDailyLoginDialog();
    }

    if (this.showReward) {
      this.renderRewardPopup();
    }
  }

  /**
   * 渲染背景
   */
  renderBackground() {
    const mainBg = this.resourceManager.getImage('mainBg');
    if (mainBg) {
      this.ctx.drawImage(mainBg, 0, 0, this.screenAdapter.DESIGN_WIDTH, this.screenAdapter.DESIGN_HEIGHT);
    }
  }

  /**
   * 渲染顶部区域
   */
  renderTopSection() {
    this.renderUserAvatar();
    this.renderUsername();
    this.renderShareSection();
  }

  /**
   * 渲染用户头像
   */
  renderUserAvatar() {
    const defaultAvatar = this.resourceManager.getImage('defaultAvatar');
    if (defaultAvatar) {
      this.ctx.drawImage(
        defaultAvatar,
        UI_CONSTANTS.TOP_SECTION.AVATAR.X,
        UI_CONSTANTS.TOP_SECTION.AVATAR.Y,
        UI_CONSTANTS.TOP_SECTION.AVATAR.WIDTH,
        UI_CONSTANTS.TOP_SECTION.AVATAR.HEIGHT
      );
    }
  }

  /**
   * 渲染用户名
   */
  renderUsername() {
    const userData = this.userManager.getUserData();
    this.textRenderer.drawText(
      userData.user_name,
      UI_CONSTANTS.TOP_SECTION.USERNAME.X,
      UI_CONSTANTS.TOP_SECTION.USERNAME.Y,
      `${UI_CONSTANTS.FONT_SIZES.USERNAME}px ${this.textRenderer.systemFont}`,
      UI_CONSTANTS.COLORS.TEXT_WHITE,
      'left',
      'top'
    );
  }

  /**
   * 渲染分享区域
   */
  renderShareSection() {
    // 分享次数文本
    this.textRenderer.drawText(
      '分享领资金：5/5',
      UI_CONSTANTS.TOP_SECTION.SHARE_TEXT.X,
      UI_CONSTANTS.TOP_SECTION.SHARE_TEXT.Y,
      `${UI_CONSTANTS.FONT_SIZES.SHARE}px ${this.textRenderer.systemFont}`,
      UI_CONSTANTS.COLORS.TEXT_WHITE,
      'left',
      'top'
    );

    // 分享按钮图标
    const shareIcon = this.resourceManager.getImage('shareIcon');
    if (shareIcon) {
      this.ctx.drawImage(
        shareIcon,
        UI_CONSTANTS.TOP_SECTION.SHARE_ICON.X,
        UI_CONSTANTS.TOP_SECTION.SHARE_ICON.Y,
        UI_CONSTANTS.TOP_SECTION.SHARE_ICON.WIDTH,
        UI_CONSTANTS.TOP_SECTION.SHARE_ICON.HEIGHT
      );
    }
  }

  /**
   * 渲染中间区域
   */
  renderMiddleSection() {
    CENTER_MENU_ITEMS.forEach((item, index) => {
      const x = this.centerMenu.x + index * (this.centerMenu.width + this.centerMenu.spacing);
      const buttonImage = this.resourceManager.getImage(item.imageKey);

      if (buttonImage) {
        this.ctx.drawImage(
          buttonImage,
          x,
          this.centerMenu.y,
          this.centerMenu.width,
          this.centerMenu.height
        );
      }
    });
  }

  /**
   * 渲染底部区域
   */
  renderBottomSection() {
    BOTTOM_MENU_ITEMS.forEach((item, index) => {
      const x = this.bottomMenu.width / 2 + index * (this.bottomMenu.spacing + this.bottomMenu.width);
      const y = this.bottomMenu.y + UI_CONSTANTS.BOTTOM_MENU.ITEM_Y_OFFSET;

      this.textRenderer.drawText(
        `${item.icon}  ${item.name}`,
        x,
        y,
        `${UI_CONSTANTS.FONT_SIZES.BOTTOM_MENU}px ${this.textRenderer.systemFont}`,
        UI_CONSTANTS.COLORS.TEXT_LIGHT,
        'center',
        'top'
      );
    });
  }

  /**
   * 渲染每日签到对话框
   */
  renderDailyLoginDialog() {
    if (this.dailyLoginDialog) {
      this.dailyLoginDialog.draw(this.ctx);
    }
  }

  /**
   * 渲染奖励弹窗
   */
  renderRewardPopup() {
    // 半透明背景
    this.ctx.fillStyle = 'rgba(0, 0, 0, 0.6)';
    this.ctx.fillRect(0, 0, this.screenAdapter.DESIGN_WIDTH, this.screenAdapter.DESIGN_HEIGHT);

    // 弹窗背景
    const gameResultPop = this.resourceManager.getImage('gameResultPop');
    if (gameResultPop) {
      const centerX = this.screenAdapter.DESIGN_WIDTH / 2;
      const centerY = this.screenAdapter.DESIGN_HEIGHT / 2;
      this.ctx.drawImage(
        gameResultPop,
        centerX - gameResultPop.width / 2,
        centerY - gameResultPop.height / 2,
        1222,
        575
      );
    }

    // 奖励金额
    this.textRenderer.drawText(
      '+',
      UI_CONSTANTS.REWARD_POPUP.PLUS_X,
      UI_CONSTANTS.REWARD_POPUP.PLUS_Y,
      `bold ${UI_CONSTANTS.FONT_SIZES.REWARD_PLUS}px ${this.textRenderer.systemFont}`,
      UI_CONSTANTS.COLORS.TEXT_YELLOW,
      'left',
      'top'
    );

    this.textRenderer.drawText(
      this.bonus,
      UI_CONSTANTS.REWARD_POPUP.BONUS_X,
      UI_CONSTANTS.REWARD_POPUP.BONUS_Y,
      `bold ${UI_CONSTANTS.FONT_SIZES.REWARD_BONUS}px ${this.textRenderer.systemFont}`,
      UI_CONSTANTS.COLORS.TEXT_YELLOW,
      'left',
      'top'
    );

    // 确定按钮
    const showRewardBtn = this.resourceManager.getImage('showRewardBtn');
    if (showRewardBtn) {
      const centerX = this.screenAdapter.DESIGN_WIDTH / 2;
      this.ctx.drawImage(
        showRewardBtn,
        centerX - showRewardBtn.width / 2,
        UI_CONSTANTS.REWARD_POPUP.BUTTON_Y,
        239,
        88
      );
    }

    this.textRenderer.drawText(
      '确 定',
      this.screenAdapter.DESIGN_WIDTH / 2,
      UI_CONSTANTS.REWARD_POPUP.BUTTON_Y + 32,
      `${UI_CONSTANTS.FONT_SIZES.REWARD_BUTTON}px ${this.textRenderer.systemFont}`,
      UI_CONSTANTS.COLORS.TEXT_WHITE,
      'center',
      'top'
    );
  }

  /**
   * 处理触摸开始事件
   */
  handleTouchStart(event) {
    // 可以在这里添加按钮按下效果
  }

  /**
   * 处理触摸结束事件
   */
  handleTouchEnd(event) {
    const touch = event.changedTouches[0];
    const logicPoint = this.screenAdapter.screenToLogic(touch.clientX, touch.clientY);

    // 处理奖励弹窗中的确定按钮
    if (this.isRewardButtonClicked(logicPoint)) {
      this.handleRewardButtonClick();
      return;
    }

    // 如果有弹窗显示，不处理其他点击
    if (this.showDailyLoginDialog || this.showReward) {
      return;
    }

    // 处理顶部区域点击
    if (this.isTopSectionClicked(logicPoint)) {
      this.handleTopSectionClick(logicPoint);
      return;
    }

    // 处理中间菜单点击
    if (this.isCenterMenuClicked(logicPoint)) {
      this.handleCenterMenuClick(logicPoint);
      return;
    }

    // 处理底部菜单点击
    if (this.isBottomMenuClicked(logicPoint)) {
      this.handleBottomMenuClick(logicPoint);
    }
  }

  /**
   * 处理触摸移动事件
   */
  handleTouchMove(event) {
    // 预留触摸移动处理逻辑
  }

  /**
   * 检查奖励按钮是否被点击
   */
  isRewardButtonClicked(point) {
    const btn = UI_CONSTANTS.DAILY_LOGIN.CLAIM_BUTTON;
    return point.x >= btn.X &&
      point.x <= btn.X + btn.WIDTH &&
      point.y >= btn.Y &&
      point.y <= btn.Y + btn.HEIGHT;
  }

  /**
   * 检查顶部区域是否被点击
   */
  isTopSectionClicked(point) {
    return point.y >= UI_CONSTANTS.TOP_SECTION.AVATAR.Y &&
      point.y <= UI_CONSTANTS.TOP_SECTION.AVATAR.Y + UI_CONSTANTS.TOP_SECTION.AVATAR.HEIGHT;
  }

  /**
   * 检查中间菜单是否被点击
   */
  isCenterMenuClicked(point) {
    return point.y >= this.centerMenu.y &&
      point.y <= this.centerMenu.y + this.centerMenu.height;
  }

  /**
   * 检查底部菜单是否被点击
   */
  isBottomMenuClicked(point) {
    return point.y >= this.bottomMenu.y &&
      point.y <= this.bottomMenu.y + this.bottomMenu.height;
  }

  /**
   * 处理奖励按钮点击
   */
  async handleRewardButtonClick() {
    if (this.showDailyLoginDialog) {
      try {
        const response = await this.api.game.applyActivities({
          activit_type: 'CHECK_IN',
        });

        this.showDailyLoginDialog = false;
        this.bonus = response.data;
        this.showReward = true;

        this.userManager.refreshUserData()
      } catch (error) {
        console.error('签到失败:', error);
        // 可以在这里添加错误提示
      }
    } else {
      this.showReward = false;
    }
  }

  /**
   * 处理顶部区域点击
   */
  handleTopSectionClick(point) {
    // 用户信息区域
    if (point.x >= UI_CONSTANTS.TOP_SECTION.AVATAR.X &&
      point.x <= UI_CONSTANTS.TOP_SECTION.AVATAR.X + 256) { // 扩大点击区域
      console.log("用户信息");
      this.pageManager.showPage('profile');
      return;
    }

    // 分享按钮区域
    if (point.x >= 1000 && point.x <= 1350) {
      console.log("分享");
      this.handleShare();
    }
  }

  /**
   * 处理分享功能
   */
  handleShare() {
    if (typeof wx !== 'undefined') {
      wx.shareAppMessage({
        title: '我在K线大师获得了新纪录，快来挑战我！',
        path: '/pages/index/index?shareFrom=button',
        imageUrl: 'https://example.com/your-custom-share-image.png'
      });
    } else {
      console.log('分享功能仅在微信小程序中可用');
      // 可以添加其他平台的分享逻辑
    }
  }

  /**
   * 处理中间菜单点击
   */
  handleCenterMenuClick(point) {
    const index = this.getCenterMenuItemIndex(point);
    if (index !== -1) {
      const item = CENTER_MENU_ITEMS[index];
      console.log(item.name);

      if (item.page) {
        this.pageManager.showPage(item.page);
      } else {
        // 功能未实现提示
        console.log(`${item.name}功能暂未实现`);
        myFn.showToast('暂未开放')
        // 可以添加功能未实现的提示
      }
    }
  }

  /**
   * 获取中间菜单项索引
   */
  getCenterMenuItemIndex(point) {
    for (let i = 0; i < CENTER_MENU_ITEMS.length; i++) {
      const x = this.centerMenu.x + i * (this.centerMenu.width + this.centerMenu.spacing);
      if (point.x >= x && point.x <= x + this.centerMenu.width) {
        return i;
      }
    }
    return -1;
  }

  /**
   * 处理底部菜单点击
   */
  handleBottomMenuClick(point) {
    const index = this.getBottomMenuItemIndex(point);
    if (index !== -1) {
      const item = BOTTOM_MENU_ITEMS[index];
      console.log(item.name);

      if (item.page) {
        this.pageManager.showPage(item.page);
      } else {
        // 功能未实现提示
        console.log(`${item.name}功能暂未实现`);
        myFn.showToast('暂未开放')
        // 可以添加功能未实现的提示
      }
    }
  }

  /**
   * 获取底部菜单项索引
   */
  getBottomMenuItemIndex(point) {
    for (let i = 0; i < BOTTOM_MENU_ITEMS.length; i++) {
      const x = this.bottomMenu.width / 2 + i * (this.bottomMenu.spacing + this.bottomMenu.width);
      if (point.x >= x - this.bottomMenu.width / 2 && point.x <= x + this.bottomMenu.width / 2) {
        return i;
      }
    }
    return -1;
  }
}
